//
//  OAuthLoginModel.swift
//  Weibo
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class OAuthLoginModel: NSObject,NSCoding {
    // "avatar_large" = "http://tp3.sinaimg.cn/5828409194/180/5747554649/1";
    //            name = "\U9a6c\U53ef_\U83e0\U841d2016";
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate.init(timeIntervalSinceNow: expires_in)
        }
    }
    var uid: String?
    var avatar_large: String?
    var name: String?
    var expires_date: NSDate?
    
    
    func saveUserInfo() {
        let docPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        let filePath: String = (docPath as NSString).stringByAppendingPathComponent("userInfo.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
        
    }
    
    class func loadUserInfo() -> OAuthLoginModel? {
        let docPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        let filePath: String = (docPath as NSString).stringByAppendingPathComponent("userInfo.plist")
        
        if let model = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? OAuthLoginModel {
            
            if model.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
                return model
            }
        }
       return nil
     }

    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init()
        
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    init(dict:[String:AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description:String {
    
        let keys: [String] = ["access_token","remind_in","uid","avatar_large","name"]
        
        let des = dictionaryWithValuesForKeys(keys)
        return des.description
    }
    
    
    
    
}













